﻿using System;
using System.Collections;
using System.IO;
using System.Linq;
using Logic.Global;
using UnityEngine;
using UnityEngine.Networking;

namespace Core.Mgr._ResMgr
{
    public class AssetBundleLoader
    {
        /// 下载角色AB时的超时限制，单位：秒
        private const int TimeOut = 60;

        /// 加载AB
        public static Coroutine LoadAssetBundle(string abName, Action<AssetBundle> finishCb = null,
            Action<float> progressCb = null, Action failCb = null)
        {
            AssetBundle.UnloadAllAssetBundles(false);
            return GameRoot.Ins.StartCoroutine(_LoadAssetBundle(abName, finishCb, progressCb, failCb));
        }

        private static IEnumerator _LoadAssetBundle(string abName, Action<AssetBundle> finishCb,
            Action<float> progressCb, Action failCb)
        {
            Debug.Log($"尝试从缓存加载:{abName}");
            string abCachePath = AppConst.AssetCachePath($"{abName}");
            if (!File.Exists(abCachePath))
            {
                Debug.Log($"从缓存加载失败，尝试从本地加载：{abName}");
                string abLocalPath = $"{Application.streamingAssetsPath}/Local/{abName}";
                if (!File.Exists(abLocalPath))
                {
                    Debug.Log($"从本地加载失败，尝试从服务器加载:{abName}");
                    string abServerDetailPath = AppConst.AssetServerUrl + $"/{abName}";
                    UnityWebRequest webRequest = UnityWebRequest.Get(abServerDetailPath);
                    webRequest.downloadHandler = new DownloadHandlerFile(abCachePath);
                    webRequest.timeout = TimeOut;
                    webRequest.SendWebRequest();
                    DateTime startTime = DateTime.Now;
                    while (!webRequest.isDone)
                    {
                        yield return null;
                        progressCb?.Invoke(webRequest.downloadProgress);
                        // Debug.Log($"{abName}下载中：{webRequest.downloadProgress}");
                    }

                    if (webRequest.result != UnityWebRequest.Result.Success)
                    {
                        Debug.LogError($"{abName}下载失败!!!");
                        failCb?.Invoke();
                    }
                    else
                    {
                        DaDianMgr.Task("loading_duration", "duration", (DateTime.Now - startTime).TotalSeconds,
                            "assetName", abName);
                        yield return
                            GameRoot.Ins.StartCoroutine(_LoadAssetBundle(abName, finishCb, progressCb, failCb));
                    }
                }
                else
                {
                    var list = AssetBundle.GetAllLoadedAssetBundles().ToList();
                    AssetBundle localAssetBundle =
                        list.Find(item => abName.Contains($"{item.name}_"));
                    if (localAssetBundle != null)
                    {
                        finishCb?.Invoke(localAssetBundle);
                    }
                    else
                    {
                        AssetBundleCreateRequest localAbRequest = AssetBundle.LoadFromFileAsync(abLocalPath, 0, 467);
                        yield return localAbRequest;
                        localAssetBundle = localAbRequest.assetBundle;
                        finishCb?.Invoke(localAssetBundle);
                    }
                }
            }
            else
            {
                var list = AssetBundle.GetAllLoadedAssetBundles().ToList();
                AssetBundle assetBundle =
                    list.Find(item => abName.Contains($"{item.name}_"));
                if (assetBundle != null)
                {
                    finishCb?.Invoke(assetBundle);
                }
                else
                {
                    var abRequest = AssetBundle.LoadFromFileAsync(abCachePath, 0, 467);
                    yield return abRequest;
                    assetBundle = abRequest.assetBundle;
                    finishCb?.Invoke(assetBundle);
                }
            }
        }
    }
}